const jsonwebtoken = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config.development')
const auth = async (ctx, next) => {
    var { authorization = "" } = ctx.request.header;
    authorization = authorization.replace('Bearer ', '')
    try {
        // user中包含了 jwt加密时的相关信息
        const user = jsonwebtoken.verify(authorization, JWT_SECRET)
        ctx.state.user = user
    } catch (err) {
        if (err.name) {
            switch (err.name) {
                case 'TokenExpiredError':
                    ctx.body = {
                        code: 401,
                        message: 'token过期!'
                    }
                    break;
                case 'JsonWebTokenError':
                    ctx.body = {
                        code: 401,
                        message: 'token无效!'
                    }
                    break;
                default:
                    ctx.body = {
                        code: 401,
                        message: 'token错误!'
                    }
            }
            return
        } else {
            ctx.body = {
                code: 401,
                message: 'token错误!'
            }
            return
        }
    }
    await next()
}

// 判断是否有权限
const hasAdminPermission = async (ctx, next) => {
    const is_admin = ctx.state.user.is_admin
    if (!is_admin) {
        ctx.body = {
            code: 403,
            message: '您当前没有权限!'
        }
        return
    }
    await next()
}
module.exports = {
    auth,
    hasAdminPermission
};